#!/usr/bin/env node

const http = require('http'),
      qs = require('querystring');
let items = [];

function err(res){
  res.statusCode = 404;
  res.setHeader('Content-Type','text/plain');
  res.end('404 Not Found');
}
function show(res){
  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset='utf-8'>
        <title>todolist</title>
      </head>
      <body>
        <h1>To Do List</h1>
        <form method='post' action='/'>
          <input type='text' name='item' />
          <input type='submit' value='AddItem' />
        </form>
        <ul>
          ${items.map(item => '<li>'+item+'</li>').join('')}
        </ul>
      </body>
    </html>
    `;
  res.setHeader('Content-Type','text/html');
  res.statusCode = 200;
  res.end(html);
}
function add(req,res){
  let body = '';
  req.on('data',chunk => body += chunk);
  req.on('end',() => {
    console.log(body);
    let item = qs.parse(body).item;
    items.push(item);
    show(res);
  }) 
}
http.createServer((req,res) => {
  if(req.url != '/'){
    err(res);
    return ;
  }
  switch(req.method){
    case 'GET':
      show(res);
      break;
    case 'POST':
      add(req,res);
      break;
    default:
      err(res);
      break;
  }
}).listen(8080);
